package com.init.bootframe.system.service.impl;

import com.init.bootframe.system.service.IUploadFileService;
import com.init.bootframe.util.TmompConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 */
@Service
public class UploadFileServiceImpl implements IUploadFileService {

    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(UploadFileServiceImpl.class);

    @Value("${server.servlet.context-path}")
    private String projectName;  // 项目名称

    @Value("${custom.file.upload}")
    private String uploadPath; // 文件储存盘符地址

    /**
     * 文件上传方法实现类
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> uploadFile(MultipartFile file, String filePath) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        String fileName = file.getOriginalFilename();
        String[] fileNames = fileName.split("\\.");
        // 保存新文件名字
        String newName = String.valueOf(System.currentTimeMillis()) + "." + fileNames[1];
        filePath = File.separator + projectName + File.separator + filePath + File.separator;
        // 数据库路径
        String newPath = File.separator + "upload" + filePath + newName;
        logger.debug("数据库保存路径"+ newPath);
        // 磁盘路径
        String newFilePath = uploadPath + filePath;
        // 如果目录不存在则创建
        File uploadDir = new File(newFilePath);
        // 文件存放到file目录下,如果该文件夹不存在,则创建
        if (!uploadDir.exists() && !uploadDir.isDirectory()) {
            boolean mkdirs = uploadDir.mkdirs();
            if (!mkdirs) {
                logger.error("创建目录失败！！！");
            }
        }
        // 转存文件
        file.transferTo(new File(newFilePath + newName));
        logger.debug("文件保存成功"+ newFilePath);
        resultMap.put("oldName", fileNames[0]);
        resultMap.put("fileName", newName);
        resultMap.put("url", newPath);


        resultMap.put("result",Boolean.TRUE);
        resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "上传文件成功！");
        return resultMap;
    }
}
